<script setup name="AttachmentSelector">
import { ElMessage } from 'element-plus';
import { useResourceApi } from '/@/api/resource';
import { isEmpty } from '/@/utils';
import AttachmentIcon from '/@/components/attachmentSelector/AttachmentIcon.vue';

const { getAttachmentList, getAttachmentListByTime, getAttachmentTimeList, attachmentServer } = useResourceApi();

// expects props options
const props = defineProps({
	maxLength: {
		type: Number,
		default: 100,
	},
});

const emit = defineEmits(['setAddState', 'checkFun']);

let loading = ref(false);
let imgList = ref([]);
let timeList = ref([]);
let keyWord = ref('');
let moreIndex = ref(0);
let isSearch = ref(false);

// 获取日期
getTimeList();
let list = getSelectItems();
//console.log(list);

async function getTimeList() {
	// 获取完日期之后去查询对应的日期的数据，避免数据量过多的问题
	loading.value = true;
	try {
		let res = await getAttachmentTimeList();
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		timeList.value = res.data;
		getList();
	} catch (error) {
		loading.value = false;
	}
}

async function getList() {
	isSearch.value = false;
	loading.value = true;
	let params = [timeList.value[moreIndex.value]];
	try {
		let res = await getAttachmentListByTime(params);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		let newItems = res.data[0].imgList.map((item, index) => {
			return {
				isChecked: false,
				id: item.id,
				orderNumber: index + 1,
				name: item.picName,
				size: item.width ? item.width + '*' + item.height : '-',
				uploadDate: item.createTime,
				imgUrl: attachmentServer + item.picUrl,
				fullName: item.imgUrl,
			};
		});
		let newList = {
			date: `${timeList.value[moreIndex.value]}`,
			items: newItems,
		};
		imgList.value.push(newList);
	} catch (error) {
		loading.value = false;
	}
}

async function getSearchList() {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let params = {
			current: 1,
			pageSize: 999,
			picName: keyWord.value,
			status: 1, // 如果是null，表示查所有，是否展示 0->禁用；1->启用
		};
		let res = await getAttachmentList(params);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;

		let newItems = res.data.data.map((item, index) => {
			return {
				id: item.id,
				orderNumber: index + 1,
				name: item.picName,
				uploadDate: item.createTime,
				imgUrl: attachmentServer + item.picUrl,
				fullName: item.imgUrl,
			};
		});

		let newList = {
			date: '搜索结果',
			items: newItems,
		};
		imgList.value = [newList];
	} catch (error) {
		ElMessage({
			type: 'error',
			message: '获取附件列表失败',
		});
	}
}

function loadNextDay() {
	moreIndex.value++;
	getList();
}

function searchFun() {
	if (loading.value) {
		return;
	}
	moreIndex.value = 0;
	imgList.value = [];
	// 需要做判断，如果是空的话就去查询列表
	if (!isEmpty(keyWord.value)) {
		isSearch.value = true;
		getSearchList();
		return;
	}
	// 如果是非空的时候就去查询全部
	getList();
}

function setAddState(state) {
	emit('setAddState', state);
}

function isShowMore() {
	let state = true;
	if (timeList.value.length === 0) {
		state = false;
	}
	if (moreIndex.value >= timeList.value.length - 1) {
		state = false;
	}
	if (isSearch.value) {
		state = false;
	}
	return state;
}

function checkItem(ceilIndex, index, checked) {
	let length = getCheckLength();
	if (props.maxLength === 1) {
		clearCheck();
		imgList.value[ceilIndex].items[index].isChecked = checked;
		let checkList = getSelectItems();
		emit('checkFun', checkList);
		return;
	}
	if (checked && length >= props.maxLength) {
		return;
	}
	imgList.value[ceilIndex].items[index].isChecked = checked;
	let checkList = getSelectItems();
	emit('checkFun', checkList);
}

function getCheckLength() {
	let length = 0;
	for (let index = 0; index < imgList.value.length; index++) {
		const element = imgList.value[index];
		for (let cindex = 0; cindex < element.items.length; cindex++) {
			const celement = element.items[cindex];
			if (celement.isChecked) {
				length++;
			}
		}
	}
	return length;
}

function clearCheck() {
	for (let index = 0; index < imgList.value.length; index++) {
		let element = imgList.value[index];
		for (let cindex = 0; cindex < element.items.length; cindex++) {
			let celement = element.items[cindex];
			if (celement.isChecked) {
				celement.isChecked = false;
			}
		}
	}
}

// 外部使用返回选中的附件
function getSelectItems() {
	let tempList = [];
	for (let index = 0; index < imgList.value.length; index++) {
		const element = imgList.value[index];
		tempList = [...tempList, ...element.items];
	}
	let returnList = [];
	returnList = tempList.filter((item) => {
		if (item.isChecked) {
			return item;
		}
	});
	return returnList;
}
</script>

<template>
	<div class="selector-box">
		<el-row :gutter="20" class="selector-header">
			<el-col :span="12">
				<div>
					<el-input maxlength="200" v-model="keyWord" placeholder="输入附件名称搜索" class="input-with-select">
						<template #append>
							<el-button icon="Search" @click="searchFun"></el-button>
						</template>
					</el-input>
				</div>
			</el-col>
			<el-col :span="12">
				<el-button text type="primary" @click="setAddState(true)">添加本地附件</el-button>
			</el-col>
		</el-row>
		<el-row :gutter="20" class="selector-content">
			<el-col :span="24" :key="`img-list-${ceilIndex}`" v-for="(ceil, ceilIndex) in imgList">
				<div class="title">{{ ceil.date }}</div>
				<div class="img-list">
					<el-row :gutter="10">
						<el-col :span="6" :key="`img-item-${ceilIndex}-${index}`" v-for="(item, index) in ceil.items" title="点击勾选">
							<div :class="item.isChecked ? `img-item img-item-checked` : `img-item`" @click="checkItem(ceilIndex, index, !item.isChecked)">
								<!-- 这里是使用封面图 -->
								<div class="img-box">
									<AttachmentIcon :attachmentUrl="item.imgUrl" :attachmentFullName="item.imgUrl" />
									<div class="checked-mask">
										<el-icon style="width: 2em; height: 2em"><circle-check-filled style="width: 2em; height: 2em" /></el-icon>
									</div>
								</div>
								<div class="name">{{ item.name }}</div>
								<div v-if="item.size" class="size">{{ item.size }}</div>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-col>
			<el-col :span="24">
				<div class="center-box" v-show="isShowMore()">
					<el-button @click="loadNextDay()" :loading="loading" round type="primary">加载更多</el-button>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<style lang="scss" scoped>
.selector-box {
	height: 500px;
	display: flex;
	flex-direction: column;
	.selector-header {
		height: 50px;
		align-items: center;
		justify-content: center;
	}
	.selector-content {
		flex: 1;
		height: 100px;
		overflow-y: auto;
		overflow-x: hidden;
	}
	.title {
		font-size: 30px;
		font-weight: bold;
		padding: 10px 0;
	}
	.img-list {
		.img-item {
			margin-bottom: 10px;
			position: relative;
			cursor: pointer;
			.checked-mask {
				display: none;
			}
			&.img-item-checked {
				.checked-mask {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 100%;
					height: 100%;
					z-index: 3;
					background: rgba(0, 0, 0, 0.3);
					left: 0;
					top: 0;
					position: absolute;
					color: #409eff;
				}
			}
			.img-box {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 200px;
				overflow: hidden;
			}
			.name {
				font-size: 14px;
				text-align: center;
				padding: 5px 0;
			}
			.size {
				font-size: 12px;
				color: #666666;
				text-align: center;
				padding: 5px 0;
			}
		}
	}
	.center-box {
		display: flex;
		margin: 10px 0;
		align-items: center;
		justify-content: center;
	}
}
</style>
